package com.charactereducation.admin.service.impl;

import com.charactereducation.dao.RoleMapper;
import com.charactereducation.dao.RoleMenuRelativeMapper;
import com.charactereducation.module.Role;
import com.charactereducation.module.RoleMenuRelative;
import com.charactereducation.admin.service.RoleService;
import com.charactereducation.tools.myRunTime.MyRunTimeExcption;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Baggio on 2017/3/12.
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    RoleMenuRelativeMapper roleMenuRelativeMapper;

    @Override
    public List<Role> getRoleList(Map<String, String> map) {
        return roleMapper.selectRoleList(map);
    }

    @Transactional
    @Override
    public void modifyRole(Map<String, String> map) {
        String tid = map.get("tid");
        String menuIds = map.get("menuIds");
        String menuIdAry[] = menuIds.split(",");
        Role role = roleMapper.selectRole(map);
        roleMenuRelativeMapper.deleteRoleMenuRelative(role.getTid());
        for (String menuId : menuIdAry) {
            RoleMenuRelative roleMenuRelative = new RoleMenuRelative();
            roleMenuRelative.setRoleId(role.getTid());
            if (menuId != "") {
                roleMenuRelative.setMenuId(Integer.parseInt(menuId));
            }
            roleMenuRelativeMapper.insertRoleMenuRelative(roleMenuRelative);
        }
    }

    @Override
    public void addRole(Map<String, String> map) {
        Role role = new Role();
        System.out.println(map.get("tid") + ".................");
        if (map.get("tid") == "") {
            String roleName = map.get("roleName");
            if (StringUtils.isBlank(roleName)) {
                throw new MyRunTimeExcption("roleName is null");
            }
            role.setRoleName(roleName);
            role.setCreateTime(new Date());
            roleMapper.insertRole(role);
        } else {
            Long tid = Long.parseLong(map.get("tid"));
            String roleName = map.get("roleName");
            if (StringUtils.isBlank(roleName)) {
                throw new MyRunTimeExcption("roleName is null");
            }
            role.setTid(tid);
            role.setRoleName(roleName);
            roleMapper.updateRoleById(role);
        }
    }

    @Override
    public Role selectRole(Map<String, String> map) {
        return roleMapper.selectRole(map);
    }
}
